<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.4.3/vue-router.js"></script>
  </head>
  <body>
    <div id="app">
      <router-link to="/home">首页</router-link>
      <router-link to="/news">新闻</router-link>
      <router-link to="/music">音乐</router-link>
      <router-link to="/login">登录</router-link>
      <router-view></router-view>
    </div>
    <template id="login">
      <div>
        <input type="text" name="uname" id="uname" v-model="username" />
        <input type="text" name="upwd" id="upwd" v-model="password" />
        <button type="button" @click="login">登录</button>
      </div>
    </template>
    <script>
      const home = { template: "<div>首页</div>" };
      const news = { template: "<div>新闻</div>" };
      const music = { template: "<div>音乐</div>" };
      const login = {
        template: "#login",
        data() {
          return {
            username: "",
            password: "",
          };
        },
        methods: {
          login() {
            this.sendRequest(
              "/user/login",
              function success(data) {
                console.log(data);
              },
              function failure(err) {
                console.log(err);
              }
            );
          },
          createXMLHttpRequest() {
            if (window.XMLHttpRequest) {
              var xhr = new XMLHttpRequest();
            } else {
              xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            return xhr;
          },
          sendRequest(url, fnSuc, fnFail) {
            xhr = this.createXMLHttpRequest();
            xhr.open(
              "post",
              url + `?uname=${this.username}&upwd=${this.password}`,
              true
            );
            xhr.onreadystatechange = () => {
              if (xhr.readyState == 4 && xhr.status == 200) {
                fnSuc(xhr.responseText);
              } else {
                fnFail(xhr.status);
              }
            };
            xhr.send();
          },
        },
      };

      const routes = [
        { path: "/", name: "default", redirect: "/home" },
        { path: "/home", name: "home", component: home },
        { path: "/news", name: "news", component: news },
        { path: "/music", name: "music", component: music },
        { path: "/login", name: "login", component: login },
      ];

      const router = new VueRouter({
        routes,
      });

      let vm = new Vue({
        el: "#app",
        data() {
          return {};
        },
        router,
      });
    </script>
  </body>
</html>
